<template>
  <view class="detail-page">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="handleBack">
        <uni-icons type="left" size="20" color="white" />
        返回
      </view>
      <view class="fav-btn" @click="toggleFavorite">
        <uni-icons :type="isFavorite ? 'heart-filled' : 'heart'" size="24" color="white" />
      </view>
    </view>
    <!-- 加载状态 -->
    <view v-if="loading" class="loading">
      <uni-icons type="spinner-cycle" size="30" :animation="true"></uni-icons>
      <text>加载中...</text>
    </view>

    <!-- 错误提示 -->
    <view v-else-if="error" class="error">
      <text>{{ error }}</text>
      <button @click="loadSpeciesData(speciesData?._id)">重试</button>
    </view>

    <!-- 内容展示 -->
    <block v-else>
      <!-- 多媒体展示 -->
      <swiper class="gallery" :autoplay="false" indicator-dots>
        <swiper-item v-for="(img, index) in speciesData?.images" :key="index">
          <image :src="img" mode="aspectFill" @click="previewImage(index)" />
        </swiper-item>
      </swiper>

      <!-- 基础信息 -->
      <view class="info-card">
        <view class="scientific-name">
          <text>学名：</text>
          <text>{{speciesData?.scientificName}}</text>
        </view>
        <view class="meta-info">
          <view class="info-item danger-level">
            <text class="label">危险等级：</text>
            <text class="stars">{{ dangerStars }}</text>
          </view>
          <view class="info-item">
            <text class="label">原产地：</text>
            <text>{{ speciesData?.origin }}</text>
          </view>
        </view>
      </view>

      <!-- 交互标签页 -->
      <view class="tabs">
        <text v-for="tab in tabs" :key="tab.id" :class="['tab-item', { active: activeTab === tab.id }]"
          @click="activeTab = tab.id">
          {{ tab.label }}
        </text>
      </view>

      <!-- 标签内容 -->
      <view class="tab-content">
        <!-- 生物特性 -->
        <view v-show="activeTab === 'biology'">
          <detail-item icon="info" title="基本特征" :content="speciesData?.features" />
          <environment-chart :data="speciesData?.careGuide" />
        </view>

        <!-- 法律信息 -->
        <view v-show="activeTab === 'legal'">
          <legal-notice :data="speciesData?.legalNotice" />
          <button class="warning-btn" @click="showLegalGuide">
            <uni-icons type="alert" size="16" />
            饲养许可申请指南
          </button>
        </view>
      </view>

      <!-- 操作栏 -->
      <view class="action-bar">
        <view class="action-buttons">
          <button class="action-btn" @click="handleLike">
            <uni-icons :type="isLiked ? 'heart-filled' : 'heart'" size="24" :color="isLiked ? '#ff4d4f' : '#666'" />
            <text>{{ speciesData?.likes || 0 }}</text>
          </button>
          <button class="action-btn" @click="showCommentInput">
            <uni-icons type="chat" size="24" color="#666" />
            <text>{{ speciesData?.comments?.length || 0 }}</text>
          </button>
        </view>
        <button class="primary-btn" @click="handleConsult">在线咨询</button>
      </view>
    </block>

    <!-- 评论输入框 -->
    <uni-popup ref="commentPopup" type="bottom" background-color="#fff">
      <view class="comment-input-container">
        <textarea v-model="commentText" placeholder="请输入评论内容" class="comment-textarea" />
        <view class="comment-actions">
          <button class="cancel-btn" @click="hideCommentInput">取消</button>
          <button class="submit-btn" @click="submitComment" :disabled="!commentText.trim()">发送</button>
        </view>
      </view>
    </uni-popup>

    <!-- 评论列表 -->
    <view class="comments-section" v-if="speciesData?.comments?.length">
      <view class="section-title">评论 ({{speciesData.comments.length}})</view>
      <view class="comment-list">
        <view v-for="(comment, index) in displayComments" :key="index" class="comment-item">
          <image class="avatar" :src="comment.avatar || '/static/userImg/user.png'" mode="aspectFill" />
          <view class="comment-content">
            <view class="comment-header">
              <text class="username">{{comment.username}}</text>
              <view class="time">
                <uni-dateformat :date="comment.createTime" :threshold="[0,3600*24*30]"
                  format="yyyy-MM-dd"></uni-dateformat>
              </view>
            </view>
            <text class="comment-text">{{comment.content}}</text>
          </view>
        </view>
      </view>
      <view v-if="speciesData.comments.length > 5" class="view-more" @click="showAllComments">
        <text>{{ showingAll ? '收起' : '查看更多' }}</text>
        <uni-icons :type="showingAll ? 'top' : 'bottom'" size="14" color="#666" />
      </view>
    </view>
  </view>
</template>

<script>
  import EnvironmentChart from '@/components/environment-chart.vue';
  import LegalNotice from '@/components/legal-notice.vue';
  import DetailItem from '@/components/detail-item.vue';
  import {
    useSpeciesStore
  } from '@/stores/species';

  export default {
    components: {
      EnvironmentChart,
      LegalNotice,
      DetailItem
    },
    data() {
      return {
        activeTab: 'biology',
        tabs: [{
            id: 'biology',
            label: '生物特性'
          },
          {
            id: 'legal',
            label: '法律要求'
          }
        ],
        speciesData: null,
        loading: false,
        error: null,
        isLiked: false,
        commentText: '',
        showingAll: false
      };
    },
    computed: {
      isFavorite() {
        return this.$speciesStore.favorites.includes(this.speciesData?.id);
      },
      dangerStars() {
        if (!this.speciesData?.threatLevel) return '';
        const level = parseInt(this.speciesData.threatLevel) || 0;
        return '★'.repeat(level) + '☆'.repeat(5 - level);
      },
      displayComments() {
        if (!this.speciesData?.comments) return [];
        console.log(this.speciesData.comments)
        return this.showingAll ?
          this.speciesData.comments :
          this.speciesData.comments.slice(0, 3);
      }
    },
    onLoad(options) {
      if (!options.name) {
        this.error = '缺少物种名称参数';
        return;
      }
      this.loadSpeciesData(options.name);
    },
    methods: {
      handleBack() {
        // 统一导航返回方法
        if (getCurrentPages().length > 1) {
          uni.navigateBack()
        } else {
          uni.switchTab({
            url: '/pages/home/home'
          }) // 无页面栈时返回首页
        }
      },

      async loadSpeciesData(species_name) {
        this.loading = true;
        try {
          // 调用获取物种详情的云函数
          const res = await uniCloud.callFunction({
            name: 'getSpeciesDetail',
            data: {
              species_name
            }
          });

          if (res.result.code === 200) {
            this.speciesData = res.result.data[0];

            // 加载评论数据
            const commentsRes = await uniCloud.callFunction({
              name: 'getComments',
              data: {
                species_id: this.speciesData._id
              }
            });

            if (commentsRes.result.code === 200) {
              this.speciesData.comments = commentsRes.result.data;
            }
          } else {
            this.error = res.result.message || '获取数据失败';
          }
        } catch (error) {
          this.error = error.message || '服务器错误';
        } finally {
          this.loading = false;
        }
      },
      previewImage(index) {
        if (!this.speciesData?.images) return;
        uni.previewImage({
          current: index,
          urls: this.speciesData.images
        });
      },
      toggleFavorite() {
        if (!this.speciesData) return;
        this.$speciesStore.toggleFavorite(this.speciesData.id);
      },
      showLegalGuide() {
        uni.navigateTo({
          url: '/pages/legal-guide/legal-guide'
        });
      },
      handleConsult() {
        uni.showModal({
          title: '专家咨询',
          content: '即将跳转至客服系统'
        });
      },
      async handleLike() {
        try {
          const res = await uniCloud.callFunction({
            name: 'toggleLike',
            data: {
              species_id: this.speciesData._id,
              is_liked: !this.isLiked
            }
          });

          if (res.result.code === 200) {
            this.isLiked = !this.isLiked;
            this.speciesData.likes = this.isLiked ?
              (this.speciesData.likes || 0) + 1 :
              (this.speciesData.likes || 0) - 1;
          } else {
            uni.showToast({
              title: res.result.message,
              icon: 'none'
            });
          }
        } catch (error) {
          uni.showToast({
            title: '操作失败',
            icon: 'none'
          });
        }
      },
      showCommentInput() {
        this.$refs.commentPopup.open();
      },
      hideCommentInput() {
        this.$refs.commentPopup.close();
      },
      async submitComment() {
        if (!this.commentText.trim()) return;

        try {
          const res = await uniCloud.callFunction({
            name: 'addComment',
            data: {
              species_id: this.speciesData._id,
              content: this.commentText.trim(),
              user_info: {
                username: '用户' + Math.floor(Math.random() * 1000), // 临时使用随机用户名
                avatar: '/static/userImg/user.png'
              }
            }
          });

          if (res.result.code === 200) {
            // 添加新评论到列表
            if (!this.speciesData.comments) {
              this.speciesData.comments = [];
            }
            this.speciesData.comments.unshift(res.result.data);
            this.commentText = '';
            this.hideCommentInput();

            uni.showToast({
              title: '评论成功',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: res.result.message,
              icon: 'none'
            });
          }
        } catch (error) {
          uni.showToast({
            title: '评论失败',
            icon: 'none'
          });
        }
      },
      showAllComments() {
        this.showingAll = !this.showingAll;
      }
    },
    beforeCreate() {
      this.$speciesStore = useSpeciesStore();
    }
  };
</script>

<style lang="scss">
  .nav-bar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    padding: 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .back-btn {
      width: 120rpx;
      padding: 10rpx 20rpx;
      background: rgba(0, 0, 0, 0.3);
      border-radius: 40rpx;
      color: #fff;
      border: none;
      display: flex;
      align-items: center;
      font-weight: bold;

      .uni-icons {
        margin-right: 8rpx;
      }
    }

    .fav-btn {
      width: 80rpx;
      height: 80rpx;
      background: rgba(0, 0, 0, 0.3);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .detail-page {
    padding-bottom: 70rpx;

    .loading,
    .error {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 400rpx;
      color: #666;

      button {
        margin-top: 20rpx;
        padding: 10rpx 30rpx;
        background: #5cb85c;
        color: white;
        border-radius: 8rpx;
      }
    }

    .gallery {
      height: 500rpx;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .info-card {
      padding: 20rpx;
      background: #fff;

      .scientific-name {
        font-size: 32rpx;
        color: #666;
        margin-bottom: 20rpx;
      }

      .meta-info {
        display: flex;
        flex-direction: column;
        gap: 15rpx;

        .info-item {
          display: flex;
          align-items: center;
          color: #666;
          font-size: 32rpx;

          .label {
            color: #666;
            font-size: 32rpx;
          }
        }

        .danger-level {
          .stars {
            color: #ff4d4f;
            font-size: 32rpx;
            margin-left: 4rpx;
          }
        }
      }
    }

    .tabs {
      display: flex;
      border-bottom: 1px solid #eee;

      .tab-item {
        flex: 1;
        text-align: center;
        padding: 20rpx;
        color: #666;

        &.active {
          color: #5cb85c;
          border-bottom: 4rpx solid #5cb85c;
        }
      }
    }

    .action-bar {
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
      display: flex;
      background: rgba(255, 255, 255, 0.9);
      padding: 12rpx 20rpx;
      box-shadow: 0 -1rpx 6rpx rgba(0, 0, 0, 0.05);
      justify-content: space-between;
      align-items: center;
      box-sizing: border-box;
      z-index: 99;
      backdrop-filter: blur(10px);

      .action-buttons {
        display: flex;
        gap: 30rpx;
        margin-left: 30rpx;
      }

      .action-btn {
        background: none;
        border: none;
        padding: 0;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 8rpx;
        min-width: auto;
        line-height: 1;
        outline: none;

        &::after {
          display: none;
        }

        text {
          color: #666;
          font-size: 28rpx;
        }
      }

      .primary-btn {
        width: 200rpx;
        height: 64rpx;
        line-height: 64rpx;
        background: #5cb85c;
        color: white;
        border-radius: 32rpx;
        font-size: 28rpx;
        padding: 0;
      }
    }

    .comment-input-container {
      background: #fff;
      padding: 20rpx;
      border-radius: 20rpx 20rpx 0 0;

      .comment-textarea {
        width: 100%;
        height: 200rpx;
        padding: 20rpx;
        box-sizing: border-box;
        border: 1px solid #eee;
        border-radius: 8rpx;
        font-size: 28rpx;
      }

      .comment-actions {
        display: flex;
        justify-content: flex-end;
        gap: 20rpx;
        margin-top: 20rpx;

        button {
          width: 160rpx;
          font-size: 28rpx;

          &.cancel-btn {
            background: #f5f5f5;
            color: #666;
          }

          &.submit-btn {
            background: #5cb85c;
            color: white;

            &:disabled {
              opacity: 0.6;
            }
          }
        }
      }
    }

    .comments-section {
      margin-top: 20rpx;
      padding: 20rpx;
      background: #fff;
      margin-bottom: 20rpx;

      .section-title {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 20rpx;
      }

      .comment-list {
        .comment-item {
          display: flex;
          gap: 20rpx;
          margin-bottom: 30rpx;

          .avatar {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
          }

          .comment-content {
            flex: 1;

            .comment-header {
              display: flex;
              justify-content: space-between;
              margin-bottom: 8rpx;

              .username {
                font-size: 28rpx;
                color: #333;
              }

              .time {
                font-size: 24rpx;
                color: #999;
              }
            }

            .comment-text {
              font-size: 28rpx;
              color: #666;
              line-height: 1.5;
            }
          }
        }
      }

      .view-more {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 20rpx;
        color: #666;
        font-size: 28rpx;
        gap: 8rpx;

        &:active {
          opacity: 0.7;
        }
      }
    }
  }
</style>